无法在 c++ 中返回字符串
Cant return a string in c++?
我的头文件中有字符串名称,当我想使用 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; }
相关文章:
- 返回常量对象引用 (getter) 和仅返回字符串有什么区别?
- C 字符串返回字符串的整数/双精度/长整型值
- 如何从COM模块中的函数返回字符串数组?
- React Native (Android):无法通过 JNI 在 jobject 中返回字符串
- 我如何在函数 cpp 中返回字符串
- 我有一个返回字符串向量的函数.它需要两个字符串,并且返回一个字符串中缺少的字符串
- 格式化返回字符串C++
- 返回字符串vs通过引用传递字符串以更新值
- 如何在不使用 STL 的情况下从函数反转字符串后返回字符串C++?
- 使用 ctypes 从函数返回字符串C++会给出大的 int,而不是 char 指针
- 从 C++ 中的模板函数返回字符串和整数
- 返回字符串的散点回文计数
- C++重载字符串 [] 运算符以返回字符串和
- 返回字符串和不同向量数据类型的映射C++
- 字符串函数不返回字符串? C++
- 从函数返回字符串C++错误
- 如何在返回字符串的函数中不忽略void值
- 我想将字符串转换为 Json 格式并返回字符串向量作为答案
- C - 返回字符串时的分割故障
- 使用向量和字符串函数返回字符串