不能在c ++中返回一个字符串?

时间:2017-11-07 23:34:19

标签: c++ string return

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

如何更改getName()方法以正确返回字符串名称变量?我是c ++的新手,谢谢。 (在Person.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

Person.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;
}

2 个答案:

答案 0 :(得分:4)

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

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个对象上调用它们。

从事物的外观来看,你还应该阅读pseudo-classes and quasi-classes

答案 1 :(得分:0)

哦,你应该通知你'get'函数的返回值。 像这样:

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