c++面向对象基础

面向对象大家都差不多,就学个基本语法啥的。

一些和java,python中面向对象的区别:

1.在class内声明函数时可以直接定义函数,也可以只声明函数名而不进行定义,然后在class外面使用范围解析运算符 :: 定义该函数
2.参数名和成员变量名同名时可以用this->来调用成员变量。不带this的可能和java一样也是就近原则
3.构造函数没有返回值,也不能写void

还有一些在写下面的例子时刚了解到的东西。此前学习的是include cstdlib的时候才能调用system函数。但是这次我没有include他的时候也能调用system。在查阅相关资料(标准库头文件 <cstdlib>)后确定是cstdlib里有system函数。在询问朋友后,了解到是iosteam里已经包含了sctdlib这个库,所以在我没有include他的时候也能调用system(果然没有系统的按课本学过就是不一样)。这个东西叫progma once,大概就是会自动处理重复的include吧。

#include <iostream>
#include <string>
#include <cstdlib>

using namespace std;

class dog
{
public:
    string name;
    int age;
    int getage();

    void bark()
    {
        cout << "I'm a dog,my name is " << name << " and I'm " << age << " years old" << endl;
    }

    // 构造函数没有返回值,也不能写void
    dog() // 不带参数的构造函数
    {
        cout << "a dog is created by none arguments constructor" << endl;
    }

    dog(string name, int ag) // 带参数的构造函数
    {
        cout << "a dog is created by arguments constructor" << endl;
        this->name = name; // 参数名和成员变量同名时可以用this->  
age = ag; } }; // 也可以在类的外部使用范围解析运算符 :: 定义该函数,如下所示: int dog::getage() { return age; } int main() { dog dog1; dog1.name = "hotdog"; dog1.age = 5; dog1.bark(); cout << "the dog's age is " << dog1.getage() << endl; dog dog2("colddog", 4); dog2.bark(); system("pause"); return 0; }

另一种初始化成员变量的方法,使用了大小写区分成员变量和参数名。

class dog {
private:
    string Name;
    int Age;
public:
    dog(string name, int age):Name(name), Age(age) {}
void bark() { cout << "My name is " << Name << " age is " << Age << endl; } };

 

posted @ 2019-03-19 18:49  roadwide  阅读(228)  评论(0编辑  收藏  举报