无法在 c++ 中返回字符串

Cant return a string in c++?

本文关键字:返回 字符串 c++      更新时间:2023-10-16

我的头文件中有字符串名称,当我想使用 cpp 源文件中的 getName() 方法返回它时,我收到此错误。 "error: cannot convert 'std::string {aka std::basic_string<char>}' to 'int' in return|" .

如何更改 getName() 方法以正确返回字符串名称变量?我是 c++ 的新手,谢谢。(问题在于最后一种方法.cpp)

头文件:

#ifndef PERSON_H
#define PERSON_H
#include <string>
class Person{
private:
    int age;
    std::string name;
public:
    Person();   //constructors
    Person(int x, std::string y);
    Person(int x);
    Person(std::string y);
    Person(std::string y, int x);
    setAge(int x); //set functions
    setName(std::string x);
    getAge(); //set functions
    getName();


};
#endif

人.cpp (PROBLEM IS WITH LAST (getName())方法:

#include "Person.h"
#include <iostream>
#include <string>
//Constructor Functions
Person::Person(){ //constructor #1, constructor for no set parameters
}//end of Constructor #1
Person::Person(int x, std::string y){ //constructor #2, constructor for when 
both int age and string name are given
}//end of Constructor #2
Person::Person(int x){ //constructor #3, constructor for when only int age 
is given
}//end of Constrictor #3
Person::Person(std::string x){ //constructor #4, constructor for when only 
string name is given
}//end of Constructor #4
Person::Person(std::string y, int x){ //constructor #6, constructor that 
uses same parameters as constructor #2 but has order reversed
}//end of Constructor #6
//end of Constructor Functions

//Set Functions
Person::setAge(int x){//sets int age to the int x parameter
}//end of setAge function
Person::setName(std::string x){//sets string name to the string x parameter
}//end of setName function
//end of Set Functions

//Get Functions
Person::getAge(){//returns int age
return age;
}//end of getAge
Person::getName(){//returns string name
//PROBLEM IS HERE **********************************************
return name;
}

您需要在两个声明中指定函数的返回类型:

void setAge(int x);
void setName(std::string x);
int getAge();
std::string getName();

。和定义:

int Person::getAge(){
    return age;
}
std::string Person::getName(){
    return name;
}

对于如此微不足道的函数,直接在类定义中定义函数是很常见的:

class Person{
private:
    int age;
    std::string name;
public:
    // ...
    void setAge(int x) { age = x; }
    void setName(std::string x) { name = x; }
    int getAge() { return age; }
    std::string getName() { return age; }
};

您的get函数通常也应标记为const

    int getAge() const { return age; }
    std::string getName() const { return age; }

这允许在const对象上调用它们。

从外观上看,您还应该阅读伪类和准类。

哦,你应该通知你返回值到'get'函数。喜欢这个:

int getAge() { return age; }
std::string getName() { return age; }