按值确定类的作用域并传递类
Scoping and passing classes by value?
本文关键字:作用域 更新时间:2023-10-16
可能重复:
什么是"三条规则"?
以下代码最多输出垃圾或崩溃:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
class C {
public:
char* s;
C(char* s_) {
s=(char *)calloc(strlen(s_)+1,1);
strcpy(s,s_);
};
~C() {
free(s);
};
};
void func(C c) {};
void main() {
C o="hello";
printf("hello: %sn",o.s); // works ok
func(o);
printf("hello: %sn",o.s); // outputs garbage
};
我真的很想知道为什么——这个物体甚至不应该被触摸,因为我是按价值传递的。。。
在C++看来,你的代码的每一件事都是糟糕的,对不起。试试这个
#include <iostream>
class C {
std::string s;
C(const std::string& s_)
: s(s_){}
};
std::ostream& operator<<(std::ostream& os, const C& c){
return os << c.s;
}
void func(C& c){
// do what you need here
}
int main(){
C c("hello");
std::cout << c << 'n';
func(c);
std::cout << c << std::endl;
return 0;
}
在本例中,您不必担心内存分配和销毁、printf格式字符串或strcpy。它要坚固得多。
带有类的C(这就是你正在写的)是完全错误的,并且盲目地忽略了为使语言在没有开销的情况下更安全、更容易而创建的功能。
相关文章:
- 未在作用域中声明unordered_map
- 有没有一种方法可以在编译时获得作用域类名
- C++quit()函数中可能存在作用域问题
- 未在此作用域OpenCV3.4中声明cvSaveImage
- 全局作用域中函数指针的赋值
- 在类函数中初始化外部作用域变量
- 不同作用域中的静态变量和全局变量
- 是同一作用域的函数部分中的函数调用
- 未在此作用域中声明的函数和变量 (C++)
- 类作用域的类型别名"using":[何时]方法中的用法可以先于类型别名?
- 将作用域枚举转换为基础类型
- 表达式必须具有完整或无作用域的枚举图
- 在构造函数中输入对象时C++类成员作用域
- 无法让"std::enable_if"适用于无作用域枚举
- 为什么不能直接引用作用域枚举类成员,而不能为无作用域枚举生成类成员?
- 函数未在作用域中声明 / 如何结合使用 header.h、header.cpp 和 main.cpp?
- 错误:表达式必须具有算术、无作用域枚举或带有运算符重载的指针类型
- 如何在C++中访问作用域的变量输出?
- 重载时未在 C++ 的作用域错误中声明
- 作用域枚举和标准::get