gpt4 book ai didi

c++ - C++中的不同对象

转载 作者:行者123 更新时间:2023-11-28 00:34:38 26 4
gpt4 key购买 nike

此程序使用构造函数在 C++ 中显示不同类型的对象。我附上了输出的快照。在输出中,为什么没有显示创建外部对象的消息?

//Program to illustrate different type of objects
#include<iostream.h>
#include<conio.h>
#include<string.h>
class diffobjs{
public:
char msg[10];
diffobjs(char ar[]){
strcpy(msg,ar);
cout<<"\nObject created of type "<<msg;
}
~diffobjs(){
cout<<"\n"<<msg<<" object destroyed";
getch();
}
};
extern diffobjs d1("Global");
void main(){
clrscr();
diffobjs d2("Automatic");
static diffobjs d3("Static");
getch();
}

OUTPUT:

最佳答案

修复一些问题:

//Program to illustrate different type of objects

// Standard C++ headers have no .h
#include<iostream>

// Not portable
// #include<conio.h>

// This <string.h> and other C headers are replaced by c... headers
// #include<cstring>


class diffobjs{
public:
// Have a std std::string to avoid buffer overflows
std::string msg;
diffobjs(const std::string& s)
// Use initialization
: msg(s)
{
std::cout<<"Object created of type "<<msg<<'\n';
}
~diffobjs() {
std::cout<<msg<<" object destroyed"<<'\n';
}
};

// A declaration would go in a header
extern diffobjs d1;

// The definition is without 'extern'
diffobjs d1("Global");

int main(){
// Globals are initialized before main
// Remove the non-portable clrscr();
// clrscr();
std::cout << "\n[Entering Main]\n\n";
diffobjs d2("Automatic [1]");
// A static in a function is initialized only once, the static has an impact on
// the order of destruction.
static diffobjs d3("Static");
// Added
diffobjs d4("Automatic [2]");
// You might not see destruction, if you start the programm in your IDE
// Hence, remove the non-portable getch()
// getch();
std::cout << "\n[Leaving Main]\n\n";
}

关于c++ - C++中的不同对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21450326/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com