【问题标题】:How do I get the string I want into int main()?如何将我想要的字符串放入 int main()?
【发布时间】:2015-03-26 21:21:24
【问题描述】:

好的,我不知道如何解释,但这里是。我想将 Dog 和 Cat 类的名称(从返回名称)获取到 int main 中,以便它们打印出 fido.name 和 spot.name 的位置。我该怎么做?

#include "stdafx.h"
#include <iostream>
#include <string>

using namespace std;

class Dog {

   private:
      // constructor
      Dog(string name) {

         this->name = name;
         name = "Fido";
         cout << "Dog's name is " << name << endl;
      }
   public:
      static string name;
      static string GetName();

};

string Dog::GetName(){
   return name;
}

class Cat {

   private :
      // constructor
      Cat(string name) {

         this->name = name;
         name = "Fido";
         cout << "Cat's name is " << name << endl;
      }
   public :
      static string name;
      static string GetName();
};

string Cat::GetName(){
   return name;
}

int main() {

   Dog fido("Fido"); //error here stating that Dog::Dog(std::string name)
   //declared at line 13 is inaccessible 
   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 0;
}

【问题讨论】:

标签: c++ string class


【解决方案1】:

您必须将构造函数设为公开(带有标记“public:”),否则您将无法从类外部创建对象。

此外,删除所有“静态”keyworkds,因为如果您将其声明为静态,您将无法拥有超过 1 个不同的“Cats”和“Dogs”

希望对你有帮助

【讨论】:

  • 感谢您的意见。不幸的是,我不允许将构造函数公开,有什么方法可以从两个类的公共区域调用name,而不是使用fido.namespot.name
  • 好的,那么,由于 Dog 和 Cat 的名称是“静态的”,因此您不能创建对象 Dog 和 Cat(对大小写有效,但这有点奇怪)。所以删除创作,并返回到您的静态关键字,因为将需要这些。例如,您可以执行 Dog.name = "Fido" 之后 Dog.GetName() 将为您提供正确的名称 这是编程练习吗?
  • 不,除了直接访问 name 属性之外,您无法更改名称,除非您可以使用“friend”关键字 :) 另一个讨厌的 hack
  • 我已经试过了,但我想我不允许使用它:(我应该把 Dog.name = "Fido" 和 Dog.GetName() 放在哪里?
  • 代替你的行 Dog fido("Fido"); //这里的错误说明 Dog::Dog(std::string name) 简单地把 Dog.name = "Fido".在那之后,你 cout 是完全合法的,你也可以使用 Dog.GetName() 但是,因为 GetName 将保存“name”的副本,所以两个调用都可以工作。对你的猫来说显然是相同的解决方案:)
【解决方案2】:

使用GetName() 函数。

cout << "From main, the Dog's name is " << fido.GetName() << endl;
cout << "From main, the Cat's name is " << spot.GetName() << endl;

您必须将构造函数移动到类的public 部分

Dog fido("Fido");
Cat spot("Spot");

上班。

当我更多地研究你的课程时,我意识到你有更多的错误。 name 需要非static 成员变量,GetName() 需要非static 成员函数——在这两个类中。

Dog 需要类似于:

class Dog {

   public:

      Dog(string name) {

         this->name = name;
      }

      string GetName() const;

   private:

      static string name;

};

您必须对Cat 进行类似的更改。

【讨论】:

  • 但那我该怎么办Dog fido("Fido");Cat spot("Spot");
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-11-13
  • 2021-01-04
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多