CPlusPlusThings icon indicating copy to clipboard operation
CPlusPlusThings copied to clipboard

CPlusPlusThings/basic_content /const/READNE.md 中有误

Open zhangasia opened this issue 10 months ago • 2 comments

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报错。

// 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

zhangasia avatar Apr 16 '24 01:04 zhangasia

而且class Apple中,int add();的定义也需要换成int add(int num);

463f avatar May 29 '24 02:05 463f

而且class Apple中,int add();的定义也需要换成int add(int num);

都行,反正c++可以重载,可以多加一个int add(int num);

zhangasia avatar Jun 01 '24 04:06 zhangasia