We read every piece of feedback, and take your input very seriously.
To see all available qualifiers, see our documentation.
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
在 7.类中使用const 中的
7.类中使用const
// apple.cpp class Apple { private: int people[100]; public: Apple(int i); const int apple_number; void take(int num) const; int add(); int add(int num) const; int getCount() const; }; // apple.cpp Apple::Apple(int i) : apple_number(i) { } int Apple::add(int num) { take(num); return 0; } int Apple::add(int num) const { take(num); return 0; } void Apple::take(int num) const { std::cout << "take func " << num << std::endl; } int Apple::getCount() const { take(1); // add(); // error return apple_number; } int main() { Apple a(2); cout << a.getCount() << endl; a.add(10); const Apple b(3); b.add(100); return 0; } // main.cpp
此时报错,上面getCount()方法中调用了一个add方法,而add方法并非const修饰,所以运行报错。也就是说const成员函数只能访问const成员函数有误,报错是因为add()没有匹配的成员函数,应该将带有const修饰的add(int num) 注释掉才会因为没有int add(int num) const报错。
此时报错,上面getCount()方法中调用了一个add方法,而add方法并非const修饰,所以运行报错。也就是说const成员函数只能访问const成员函数
add()
const
int add(int num) const
// apple.cpp class Apple { private: int people[100]; public: Apple(int i); const int apple_number; void take(int num) const; int add(); // int add(int num) const; int getCount() const; }; // apple.cpp Apple::Apple(int i) : apple_number(i) { } int Apple::add(int num) { take(num); return 0; } /* int Apple::add(int num) const { take(num); return 0; } */ void Apple::take(int num) const { std::cout << "take func " << num << std::endl; } int Apple::getCount() const { take(1); // add(1); // error return apple_number; } int main() { Apple a(2); cout << a.getCount() << endl; a.add(10); const Apple b(3); b.add(100); return 0; } // main.cpp
The text was updated successfully, but these errors were encountered:
而且class Apple中,int add();的定义也需要换成int add(int num);?
class Apple
int add();
int add(int num);
Sorry, something went wrong.
都行,反正c++可以重载,可以多加一个int add(int num);
No branches or pull requests
在
7.类中使用const
中的此时报错,上面getCount()方法中调用了一个add方法,而add方法并非const修饰,所以运行报错。也就是说const成员函数只能访问const成员函数
有误,报错是因为add()
没有匹配的成员函数,应该将带有const
修饰的add(int num) 注释掉才会因为没有int add(int num) const
报错。The text was updated successfully, but these errors were encountered: