如何将我想要的字符串输入到int main()中

How do I get the string I want into int main()?

本文关键字:main int 输入 我想要 字符串      更新时间:2023-10-16

好的,我不知道如何解释,但现在开始。我想将Dog和Cat类的name(从返回名称)输入到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;
}

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

此外,删除所有"静态"密钥,因为如果你将其声明为静态,你将无法拥有超过1个不同的"猫"answers"狗"

我希望它能帮助

使用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进行类似的更改。