【问题标题】:My get function isn't working我的获取功能不起作用
【发布时间】:2015-03-26 14:40:26
【问题描述】:
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;
}

【问题讨论】:

  • @Paul Merimee 尝试按照您正在阅读的书中显示的方式键入代码。
  • 顶部被切断了。这是一个类还是一个结构?
  • 你应该得到语法错误,因为int main Cat::getname() { 是无效的语法。
  • 你的问题是什么?说清楚

标签: c++ get


【解决方案1】:

要从对象中获取名称,您需要使用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 的类定义。

【讨论】:

  • 感谢您的回复!除了我仍然得到这个 [IntelliSense: "Dog::Dog(std::string name)" (declared at line 15) is inaccessible] 错误。我该如何解决这个问题?
  • 用你的水晶球看看我的答案或发布你的Dog类的定义。提示:privateprotectedpublic 部分中的构造函数是否在您的类中?
  • 这是我的狗类。类狗{公共:字符串getname;字符串名称; private: // 构造函数 Dog(static string name) { this->name = name; cout
  • 再试一次。 编辑您的问题并将定义放在那里。不要将代码放在 cmets 中,因为它很难阅读(您可以轻松阅读评论中的代码吗?)。
  • 构造函数是私有的。
猜你喜欢
  • 2015-07-26
  • 2021-02-25
  • 1970-01-01
  • 1970-01-01
  • 2012-07-15
  • 2012-03-20
  • 2019-08-18
  • 1970-01-01
  • 2022-01-24
相关资源
最近更新 更多