我的get函数不起作用

时间:2015-03-26 14:40:27

标签: c++ get

class Cat {
public:
    string getname() const;
    void setname(string name);

private:
    string name;
    // constructor
    Cat(string name) {

        this->name = name;
        cout<<"Cat's name is "<< name << endl;
    }
};

int main Cat::getname() {

    string name ="Assignment 09";
    cout << name << endl;
    Dog fido("Fido");
    Cat spot("Spot");
    cout <<"From main, the Dog's name is "<< fido.name << endl;
    cout <<"From main, the Cat's name is "<< spot.name << endl;

    cout <<"Hit any key to continue"<< endl;

    system("pause");

    return name;
}

1 个答案:

答案 0 :(得分:0)

要从对象中获取名称,您需要使用getname方法:

// Note the removal of Cat::getname()
int main (void)
{

    string name ="Assignment 09";
    cout << name << endl;
    Dog fido("Fido");
    Cat spot("Spot");

    // Note the changes here:  fido.getname()
    cout <<"From main, the Dog's name is "<< fido.getname() << endl;

    // Similarly:  spot.getname()
    cout <<"From main, the Cat's name is "<< spot.getname() << endl;

    cout <<"Hit any key to continue"<< endl;

    system("pause");

    return name;
}  

fido.getname()是一个假设,因为您未在问题中提供Dog的类定义。