2014-01-30 5 views
0

Эта программа отображает различные типы объектов в C++ с использованием конструктора. Я приложил снимок вывода. На выходе, почему нет сообщения, отображаемого для создания внешнего объекта?Различные объекты в 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:

+1

ваша программа не C++ программы, пожалуйста, переформулировать ваш вопрос. – user2485710

+7

удалите clrscr(); –

+1

@ user2485710 ... Итак, каково ваше определение C++? – sgarizvi

ответ

1

Строка с экстерном ключевым словом не определяет объект, но только вперед объявляет его. Если вы удалите это ключевое слово и оставите остальную часть строки, будет создан глобальный объект.

2

Закрепление некоторые вопросы:

//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"; 
} 
Смежные вопросы