以这种方式在c ++中操作字符串是可以的:
string s = "Sting";
s[2] = 'a';
Run Code Online (Sandbox Code Playgroud)
它工作正常(并打印'Stang'),但这样做是否安全?
如果是,这是否意味着它们是可变的?
版本1:
// In this, the enum is declared globally
#include <iostream>
#include <string>
using namespace std;
enum Hand {RIGHT,LEFT};
class Batsman {
public:
Batsman(string s, Hand h) {
name = s;
hand = h;
}
void setName(string s) {
name = s;
}
void setHand(Hand h) {
hand = h;
}
string getName() {
return name;
}
Hand getHand() {
return hand;
}
private:
string name;
Hand hand;
};
void main() {
Batsman B1("Ryder",LEFT);
Batsman B2("McCullum",RIGHT);
}
Run Code Online (Sandbox Code Playgroud)
版本2:
// In …Run Code Online (Sandbox Code Playgroud) 假设有一个用户定义的类Student.考虑以下两个功能:
Student someFunc1() {
return *(new Student("John",25));
}
Student& someFunc2() {
return *(new Student("John",25));
}
Run Code Online (Sandbox Code Playgroud)
没有详细说明为什么他们按照他们的方式实施,他们都是正确的吗?有人告诉我,会有内存泄漏但是怎么回事?
c++ ×3