Язык программирования C++ - ответы
Количество вопросов - 391
float arr[3] = {10, 20, 30}; float *a = arr; cout << a[1];
int *a; int b[2]; a = b; b[0] = 7; b[1] = 10; *a++; cout << *a;
k = ++k;если до его выполнения k равнялось 6?
double x = 12.4;cout << setw(5) << x << setw(3) << setfill('*')<< "" << endl;
1. class A{ public: int x; int summ(int a){return x+a;}};2. class my_cl{ public: int f; int summ(int a){return x+a;}};3. class B{ public: int F; void Ch_F(int x) { F=x; return F; }};
int main() { int x1 = 5; x1 = x2 - 2; int x2 = x1; cout << x2; return 0; }
class A { public: A() { ptr = new char[size]; Init(); } ~A() { if (ptr) delete[] ptr; } char* ptr; };произойдет исключительная ситуация, будет ли потеряна память при откате по стеку?
1: class Channel2: { public:3: void SetNumber (int n) { number = n;};4: int GetNumber() const { return number;};5: int number;};6: int main()7: { Channel ch;8: ch.number = 9;9: ch.SetNumber(10);10: Channel ch2(2);11: return 1;12: }
#include "iostream.h"#include "conio.h"#define N=10int main(){ int x=N; cout<<x; getch(); return 0;}
int calc(int a, int b, bool f) { if (f==1) return a+b; else return a*b; }
struct {char fio[30];int date, code;double salary;}staff[100], *ps;
int f(int& x) { static int a = 0; if (!a) a = ++x; return a;} int y = 6; f(y); cout << f(y) << y;
int f1(int & x1, int *x2) { return ++x1 + ++(*x2); } int main() { int a = 7, k = 1; k = f1(a, &k); cout << a << " " << k; }
class t { public: double sum::Z1;} C; class sum { public: double t::Z1;} D;
struct my{ int a, b;} m1;int func(my f){ return f.a + f.b++;}int main(){ m1.a = 5; m1.b = 10; cout << func(m1); return 0;}
int main() { int a,b,c,d; a=1; b=2; c=a+b+p; cout << p; ... }
int x = 3, y = 2, z = 1; if(x >= y) if(y <= z) std::cout << "Вариант 1"; else if(x >= z) std::cout << "Вариант 2"; else std::cout<<"Вариант 3";будет напечатано:
switch(n) {case 2: cout << "ааа"; break;case 3: cout << "ббб"; break;default: cout << "ввв"; break; }
int m = 2, n = 5; while (m <= 3) { while (m <= n) { n = m; break; } break; m++; }
int a=3;if (a>1) cout << "1";else if(a>2) cout << "2";else if(a>3) cout << "3";
1.{if (n == 1 || n == 0) return 1; else return n * fact (n -1);}2.{if (n == 1 || n == 0) return 1; else return fact(n);}
int sum(int a, int a1, int a2, int a3, int a4=2){return a+a1+a2+a3+a4;}вызвать в функции main следующим образом
int main(){ int z=1,b=1,c=1,d=1,e=1; sum(z,b,c,d,e); ....}
class A {public: int y; int inc(int x) { return ++y; }; int inc(short x) { return x + y; };};A obj; int y = 5; obj.y = 6;cout << obj.inc(y);
Team::Player p; p.GoGoGo();для класса Team, описанного следующим образом:
class Team{public: int score; class Player { public: void GoGoGo(){ printf("Player is going to a goal.\n"); } }; void SetScore(int x){ score = x;} void ShowScore(){printf("%d\n",score);}};
class Add{ public: short S1; int f(int x) { return S1 + ++x;} int A(short a, short b);} K1;int Add::A(short a, short b){ this->S1 += a*b; return this->S1; };int main(){ K1.S1 = 2; K1.f(2); K1.A(0, 1); cout << K1.S1; return 0;}
class A{ public: double sum(int double,double s2); int sum (int s1,int s2); }
struct Value {double tt; //Размер переменной типа double 64 битаunion number { short sx; // Размер переменной типа short 16 битов long lx; // Размер переменной типа long 32 бита double dx; // Размер переменной типа double 64 бита } val;};сколько байтов занимает один объект такого типа?
#include "iostream.h"#include "conio.h"int main(){ int *a; int b=7; a = &b; b+= 7; (*a)++; cout << a; getch(); return 0;}
int array[10]; array[1] = 2; array[10] = 3; cout << array[10];
...// Необходимые библиотеки подключеныstruct my{ int a, b;} m1;int func(my *f){ return f->a + f->b++;}int main(){ m1.a = 2; m1.b = 5; cout << func(&m1); return 1;}
int x=39, *p = &x; cout << p << "__" << *p ;
int f1(int x1, int &x2) { return ++x1 + (++x2); } int main() { int a = 7, k = 1; k = f1(a, k); cout << a << " " << k; }
1 int f1() { 2 char ch, ch1='a', ch2='b', ch3='c';3 ch=ch1+ch2+ch3;4 f1=int(ch);5 return f1; 6 }
class A { public: void f() { cout << 1; } }; class B : public A { public: void f() { cout << 2; } };то что будет напечатано в результате выполнения кода?
B b; A& a=b; a.f();
class Channel{ public: void SetNumber (int n) { number = n;}; int GetNumber() const { return number;}; int number;};int main(){ private : int n;} Channel ch;{Channel ch; ch.number = 9; ch.SetNumber(10); Channel ch2(2);}
class A { public : int a, b; protected : int func (float d) {}; private : short i; } A1;class B : public A { private : int k; } B1;class C : public B { protected : int l, m; } C1;
class A{ public : int a, b; protected : int z; private : short id; } A1;class B : protected A{ public : short t; void ff(short a) { id = ++a; }} B1;int main(){ B1.ff(20); cout << B1.id;}
class A { friend int Freund(); friend class B; public : int x, y; private: short i; } A1; class B { public : void func_B(); }B1; int Freund() { A1.x = 1; A1.y = 2; A1.i += 3; return A1.x + A1.y + A1.i; } void B::func_B() { A1.i = 2; } int main() { B1.func_B(); cout << Freund(); }
monstr Super(200, 300), Vasia(50), Z;monstr X = monstr(1000);monstr Y = 500;
class Complex { double real; double img; . . . };какой у него должен быть деструктор?
void* operator new(size_t size, int a);то какой вызов этой операции правильный?
long (*lp)[2][4];lp = new long[3][2][4];
A(int x);operator int();operator++(int);то какие из них будут вызваны в следующем выражении ?
A b; static_cast <int> (b + 1);
A a1,a2,a3=5;a3 = a1 – a2;
int m = 1,n=2; int *p= &n; p=static_cast<int*> (m); cout << *p;
//Пример файла test.h#ifndef TEST#define TEST//прочие строки кода#endif
S = CIRC(a + b);
char foo(char my_ch) { char ch= my_ch; static int flag = 1; if (flag){ char p; p=ch; ch=ch+1; } ..... return ch; }
...int a=9; // в глобальном пространствеvoid f() { int a; a = 4; }...cout << a;то что будет выведено?
func() { int a = 10; } int main() { int x2 = a + 1; cout << x2; return 0; }
int m = 5; namespace space1 { int x1 = 1; namespace space2 { int x1 = 3 + ::m + space1::x1; } } int main() { int x3 = space1::space2::x1 * 2; { int x3 = 20; } cout << x3; return 0; }
class A {... } A1;class B : public A { ... } B1;class C : public A { ... } C1;то что будет выведено при выполнении оператора
throw (C1);а обработка исключительной ситуации записана
catch (B& b) { cout << 1; }catch (C& c) { cout << 2; }catch (A& a) { cout << 3; }catch (...) { cout << 4; }
#include <iostream.h>short x = 4, i = 0;void fun1(){ if (i == 5) throw 2; }void fun2(){ --x; fun1(); x++; }int main(){ try { fun2(); } catch (int) { cout << "Exception "; } cout << x << " " << i;}
int main() { try{ try { throw 3.14; } catch (int) { cout << "Exception 1"; } } catch (...) { cout << "Exception 2"; } return 0; }
#include <iostream.h> int main(){ char A[] = "ABC "; char *U = &A[2]; cout << "\n" << *U--; cout << *U-- ; cout << *U; return 1;}
#include <iostream.h> #include <fstream.h> #include <string.h> int main() { int i = 1, j = 25; double a = 25e6; char s[40]; strcpy(s, "Test"); ofstream outfile("c:\\test.dat"); if (!outfile) { cout << "Ошибка создания файла"; return 1; } outfile << i << ' ' << j << ' ' << a << ' ' << s << endl; outfile.close(); }
template <class T>T func1(T a,T b){ if(a) a=a%b; return a;}Верен ли код
float a=5,b=6,c;c=func1(a,b);
1:template<class Т> class А{2:int х;3:};4:template<class Т> class А<Т*> {5:long х;6:};7:template<template<class U> class V> class C{8:V<int> y;9:V<int*> z;10:};11:C<A> c;
template <class T> T sum(T *a, T *b) { T f = 5; return (*a + *b) - f; } int main() { int i = 10, j = 20; double x = 5.1, y = 2.2; cout << sum(&i, &j) << " " << sum(&x, &y); }
if(a){ a=a%b; } else cout << error;(Желательно ответить на этот вопрос не глядя на варианты ответов)
int m = 10, n = 4; double A = static_cast <double> (m)/n; cout << A;
double func(double x, int n) { if (n == 0) return 1; if (x == 0) return 0; if (n > 0) return x * func(x, n-1); if (n < 0) return func(x, n+1) / x; }
class A {int x; double y; ... }является наиболее правильным?
_ _| 1 2 3 || 5 6 7 ||_ 9 1 2 _|Что будет на экране в результате выполнения кода
int flag=7; for (int i = 0; i<3; i++) {if (flag) cout << Ar[1][i];elsecout << "Error";}
class A {... } A1;class B : public A { ... } B1;class C : public B { ... } C1;то что будет выведено при выполнении оператора
throw (C1);а обработка исключительной ситуации записана
catch (B& b) { cout << 1; }catch (C& c) { cout << 2; }catch (A& a) { cout << 3; }catch (...) { cout << 4; }
int sum(int a,int a1=2,int a2,int a3,int a4){return a+a1+a2+a3+a4;}что будет выведено на экран после выполнения кода cout<<sum(9,8,7,6);
class Ping { public: float f, d; int a; void MathFunc(double D);};
1:class A 2: { public: void f1(int &a){val+=a++;};//val инициализируется в конструкторе 3: int const f2() {return val+1;}; 4: int val; 5: void f3(int f, const char ch); 6: } A1; 7: void A::f3(int f, const char ch){ 8: int d=5; 9: f1(*d); 10: f2(); 11: }
#include <iostream.h>short x = 4, i = 0;void fun1(){ double p=2; if (!i) throw p; }void fun2(){ --x; fun1(); x++; }int main(){ try { fun2(); } catch (double) { cout << "Exception "; } cout << x << " " << i; }
class A { const int f() { . . .}; }; g(const& A a) { a.f(); . . . }?
#include <iostream>int main() { int i; for(i = 0; i < 9; i++) std::cout << i+1; return 0;}
int x = 3, y = 2, z = 1; if(x >= y) if(y <= z) cout << "Вариант 1"; else if(x <= z) cout << "Вариант 2"; else cout << "Вариант 3";будет напечатано:
if (i == 4) cout << "aaa";else if (i == 3) cout << "bbb";else if (i != 3) cout << "ccc";
int k = 0; do { k++; if (k == 1) continue; else break; ++k; } while (k < 5);
int a=3;if (a>1) cout << "а>1";if (a>2) cout << "a>2";if (a>3) cout << "a>3";
1.{if (n == 1) return 1; else return n + sum (n - 1);}2. {if (n == 1) return 1; else return sum(n);}
if(f>d)cout << "f>d";if (f==d)cout << "f=d";if(f<d)cout <<"f<d";
class Team{public: int score; class Player { public: void GoGoGo(){ printf("Player is going to a goal.\n"); } }; void SetScore(int x){ score = x;} void ShowScore(){printf("%d\n",score);}};Выберите из нижеприведенных записей корректные коды для этого класса:
1. Team::Player p; p.GoGoGo();2. Team t;t.Player p;p.GoGoGo();
class my { public: double Z; int f(int c, int d) {return c+d;} char s; } T1, T2;
class t{ public: int sum; float f(int a) { sum++; return sum * a; }} cl;int main(){ cl.sum = 10; cout << cl.sum << " " << cl.f(4);}
{ int ar[4]; ar[0]=1; ar[1]=2; ar[2]=3; ar[3]=4; for (int i = 0; i<=4; i++) cout << ar[i]; }
int a[4] = { 1,2,3,4}; int* p = a; cout << (*p+2) + *p;
int main() { ...... float a1 = 7, a2 = 8; { float p=4; float p1=5; p1+=5; } if (a2) a1+=a2+p1++; cout << a1; ..... }
class Base{…public: void f(); private: int *baseID;};class Derived : public Base{…public: void foo();private: int derivedID;};Derived my1;int x;my1.baseID=&x;
class A { public : int a, b; protected : int z; private : short i; } A1; class B : public A { public : int c, d; private : int k;} B1;
struct str{ int a = 2; float b = 10;} m1, m2;cout << m1.a * m2.b;
...vector <int> IntVector;//объект класса вектор/*запись значений в IntVector*/int d=IntVector[0];... }
ofstream("filename", ios::out|ios::app|ios::trunc)
const char* str1 = "hello"; char* str2 = const_cast ( char* ) str1; cout << str2;
A a; int x; int y = a * x;
1 int sum(int a,int b,int c,int d=4){2 int result;3 result=128*a+b-c*d;4 d=25;5 a=d;6 return res;7 }
class A {public: int inc(int x) { return ++x; }; int inc(short x) { return x + 2; };};A obj; int y = 5;cout << obj.inc(y);
void f1() { static int flag=0; if (!flag) { cout << "false "; flag=5; } else { cout <<"true "; flag=0; }}
class A{ public : int a, b; protected : int z; private : short i; } A1;class B : protected A{ public : int c, d; private : int k; } B1;
class A { public : int a, b; protected : int z; private : short i; } A1; class B : protected A { private : int k;} B1; int main() { B1.z = 20; cout << B1.z; }
class A { CountPass(); private: short i; }A1; friend A::CountPass() { A1.i = 23;}
class Rectangle{ public: int a,b; int sum(); int square(); ~rect(); };
void operator delete(int x, void* addr)то при вызове
A* ptr; . . . delete(10, ptr);
1. Конструктор – 2. Деструктор – 3. Дружественная функция – 4. Переопределение операций - A - вызывается автоматически, как только объект класса уничтожается. B – имеет доступ к защищенным и собственным компонентам класса, не являясь его компонентом. C – возможность распространения действия стандартных операций на операнды, для которых эти операции первоначально в языке не предполагались. D – используется для инициализации объектов класса.
#define CIRC(x) (3 * (x) * (x)) #include <iostream.h> int main() { int a = 1, b = 2; std::cout << CIRC(a + b); }
#define f(x) x##4то какой будет результат после препроцессора ?
#if 4int d4;f(d) = 5;#endif
namespace a { int a; void A() { static int a = 4; }; };Какой будет результат выполнения cout << a::A::a; в функции main?
#include <iostream.h>short x = 4, i = 0;void fun1(){ if (i == 0) throw 2; }int fun2(){ --x; fun1(); x++; return x; }int main(){ try { fun2(); } catch (int) { cout << "Exception "; } cout << x << " " << i; }
int main() { try { try { try{ throw 1; } catch (float) { cout << "Exception 1"; } } catch (int){ cout << "Exception 2"; } } catch (int){ cout << "Exception 3"; } return 0; }
00000 00000Замечание:при написании собственных программ с использованием форматированного ввода/вывода подключите файл iomanip.h
#include <iostream.h>int main(){int ic; cout << "Введите любую десятичную цифру:"; cin >> ic;switch (ic) { case 0: case 1: cout << "один "; case 2: case 3: cout << "три "; case 4: case 5: cout << "пять "; case 6: case 7: cout << "семь "; case 8: case 9: cout << "девять "; break; default: cout << "ERROR!!!"; } return 1;}
int a = 7; //в глобальном пространствеvoid f() { static int a; a += 5; }и в функции main() выполняется
f(); cout << a;то какой будет результат?
template <class T> class A{ public: A(){ printf("1 ");}};template <> class A<int>{ public: A(){ printf("2 ");}};template <> class A<char*>{ public: A(){ printf("3 ");}};Какой будет результат после выполнения кода
A<int> a;A<char> a1;A<long> a2;
int main() { try { try { try { throw 1; } catch (int) { cout << "Exception 1"; } } catch (int) { cout << "Exception 2"; } } catch (int){ cout << "Exception 3"; } return 0; }
class t{ public: int sum; float f(int a, short m) { sum++; return sum * a - m; }} v;int main(){ v.sum = 5; cout << v.sum << " " << v.f(5, 2);}
class MyClass { int sz; // число элементов int * v; // указатель на целые public: MyClass ( int ); ~MyClass (); int&operator [] ( int index ); // операция индексации };…MyClass::~ MyClass() { delete [] v; }
class A {public: int inc(int x) { return ++x; }; int inc(short x) { return x + 2; };};A obj; int y = 5;cout << obj.inc(y);
class A { public : int a, b; protected : int z; private : short i; } A1; class B : private A { private : int k;} B1; int main() { B1.a = 10; cout << B1.a; }
char sss = 't';char ddd;const char* ptr = &sss;какое из следующих выражений верно:
#define myincl "D:\Project\Coding\CodingU.h" #include myincl
char foo(char my_ch) { char ch= my_ch; static int flag = 1; if (flag){ char p; p=ch; ch=ch+1; } ..... return ch; }
int a; //в глобальном пространстве void f() { extern int a; a = 8; }и в функции main() выполняется
a = 3; f(); cout << a;то какой будет результат?
namespace t { char * c = "Hi"; } int main() { char * x2 = c; cout << x2; return 0; }
ofstream outfile("c:\\test.dat",ios::in); if (!outfile) { cout << "Ошибка создания файла"; return 1; } outfile << "!!!"; outfile.close();
// файл File1.h #ifndef __File_h__ #define myconst 35 #else #define myconst 30 #endif // файл Test.cpp #include <iostream.h> #include "File1.h" int main() { cout << myconst + 10; }
1: class A 2: { public:3: int x;4: int GetX() { return x; };};5: int main() 6: { A b;7: b.SetX(2);8: b.GetX();9: A b1(2);10:}
class A{ public: void sum(double s1,double s2); int sum (int s1,int s2); };
template <class T> class Matrix { public : Matrix(int, int); ~Matrix() { } }
#include <iostream.h>int main() { int 1_i ; for( 1_i = 0; 1_i < 9; 1_i++) cout << 1_i +1; return 1;}
1:class A2: { public: void f1(int &a){val+=a++;};//val инициализируется в конструкторе3: int f2() {return val+1;}; 4: int val; 5: } A1;6:int main()7: { 8: A1.f1(); 9: A1.f2(); 10: }
// Описываются указатели:monster *p;demon *d;При выполнении какого выражения всегда можно говорить,что потери информации не будет?
class A { int x; int f(const A& a) { x = 0; x += a.x; return x; } };
1 monstr::monstr(const monstr &М){2 if (M.name){3 name = new char [strlen(M.name) + 1];4 strcpy(name, M.name);}5 else name = 0;6 health = M.health; ammo = M.ammo; skin = M.skin;7 }…8 monstr Vasia (blue);9 monstr Super = Vasia; 10 monstr *m = new monstr ("Orc");11 monstr Green = *m;
int m = 5; namespace space1 { int x1 = 3; namespace space2 { int x1 = 2 + ::m + space1::x1; } } int main() { int x3 = space1::space2::x1 * 2; { int x3 = 10; } cout << x3; return 0; }
class A {... } A1;class B : public A { ... } B1;class C : public A { ... } C1;то что будет выведено при выполнении оператора
throw (A1);а обработка исключительной ситуации записана
catch (B& b) { cout << 1; }catch (C& c) { cout << 2; }catch (A& a) { cout << 3; }catch (...) { cout << 4; }
ofstream outfile("c:\\test.dat"); if (!outfile) { cout << "Ошибка создания файла"; return 1; } outfile << "!!!" << endl; outfile.close();
template <class T> class A { public : T x1; T x2; T func(T x3) { x3 += x1 + x2; return x3; } }; int main() { A <int> A1; A1.x1 = 3; A1.x2 = 10; cout << A1.func(1); .... }
float array[5]; array[1] = 10; array[2] = 3; float array2[5]; array2 = array; cout << array2[1];
char x[] = "Hello, world"; char* p = x; p += 4; cout << *p;
ofstream outfile("c:\\test.dat",ios::in); if (!outfile) { cout << "Ошибка создания файла"; return 1; } outfile << "!!!"; outfile.close();
int func(){ int k = 10; for (int i = 0; i <= k; i++) { return 5; k = i; }}
int a = 0; float f = 3.4; a += f;