gpt4 book ai didi

c++ - 构造函数中的错误 - C++

转载 作者:行者123 更新时间:2023-11-28 00:14:02 25 4
gpt4 key购买 nike

我刚刚在 Python 中学习了一些面向对象的编程概念,但我想将这些知识转移到 C++ 中,并且我在过去使用 Python 很容易实现的基本实现方面遇到了麻烦。

#include<iostream>
using namespace std;

class Animal{

char name;
int age;

public:
Animal(char name, int age);
};

Animal::Animal(char name, int age) {
this->name = name;
this->age = age;
}

int main()
{
Animal dog ("Megg", 10);

cout << "Name: " dog.name <<endl;

return 0;
}

当我编译这段代码时,我收到了很多消息,例如:

error: no matching function for call  to 'Animal::Animal(const char[5], int)'
note: Animal::Animal(char, int) <near match>
note: candidate expects 1 argument, 2 provided

谢谢!

最佳答案

你不需要在构造函数定义中这样做->name = name

“Megg”是一个字符串文字。您可以将“Megg”转换为 const char * 但不能转换为 char(这很可能导致您的错误)。

或者更好。您可以使用 C++ 标准库字符串类 std::string

#include <iostream>
#include <string>

class Animal{

std::string name;
int age;

public:
Animal(std::string name, int age);
std::string getName() const;
int getAge() const;
};

Animal::Animal(std::string Name, int Age) {
name = Name;
age = Age;
}

std::string Animal::getName() const {
return name;
}

int Animal::getAge() const {
return age;
}

int main()
{
Animal dog ("Megg", 10);

std::cout << "Name: " << dog.getName() << std::endl; // Error in this line. Missing << between "Name: " and dog.name

return 0;
}

一些额外的编辑:

您应该避免使用 using namespace std,因为它会将标准库中的所有内容(来自您包含的文件)放入全局命名空间中。您可以改用范围解析运算符 ::,如上所示。

当您开始使用多个库时,您可能会遇到它们都有一个名为 vector 或 string 的类,或者具有相同名称的函数。避免这种情况的方法是指定您要使用的命名空间。

或者您可以执行以下操作:

using std::cout;
using std::endl;
using std::string;

另外,为了让您的程序正常工作,您需要一种方法来访问对象的成员变量。您可以通过公开变量来做到这一点,或者更好的做法是添加访问器函数。

关于c++ - 构造函数中的错误 - C++,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31486769/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com