|
|
|
Хитрый деструктор
, Или непонятнки со стандартом
- Подписаться на тему
- Сообщить другу
- Скачать/распечатать тему
|
|
ОС: Любая Народ жаловался, что нет интересных вопросов. Попробую исправить эту ситуацию. #include <iostream> struct B { ~B() {std::cout << «B::~B» << std::endl;} }; struct D : B { }; D::~D() {std::cout << «D::~D» << std::endl;} int main() { D d; }
Внимание, вопрос. Сообщение отредактировано: Flex Ferrum — 19.01.05, 16:17 |
Lucifer |
|
6-ка матерится при компиляции |
Flex Ferrum |
|
Lucifer, попробуй на 7.1 |
Lucifer |
|
Цитата Flex Ferrum @ 19.01.05, 16:28 Lucifer, попробуй на 7.1 А потом обоснуй результат. 7.1 нихт. В ней откомпилится? |
Flex Ferrum |
|
Цитата Lucifer @ 19.01.05, 16:33 7.1 нихт. В ней откомпилится? Я пока обожду с ответом на этот вопрос…. |
FlatBug |
|
Full Member Рейтинг (т): 4 |
7ёрка компилит. ерроров нет. 7ёрка рулит. она круче 6ёрки!!! Я победил? Приз в студию!!! УРА-УРА!!! Сообщение отредактировано: FlatBug — 19.01.05, 16:45 |
XE-XE |
|
definition of implicitly-declared `D::~D()’ (g++ 2.95.3) |
Шерлок Холмс |
|
Имеем: Все правильно! Добавлено 19.01.05, 17:13 Цитата XE-XE @ 19.01.05, 16:54 definition of implicitly-declared `D::~D()’ (g++ 2.95.3) В стандарте сказано, что конструкторы (копирования) и т.п., если их нет создаются компилятром. |
byte |
|
VC7.1 компилит, результат изложен выше. Цитата error: defining an implicitly declared member function is not allowed |
Шерлок Холмс |
|
byte, это значит токо, что разработчики Intel C++ не очень читали стандарт! |
byte |
|
Шерлок Холмс, дык вот в чем прикол-то. Деструктор не объявлен, но определен. И вопрос в том, как должен вести себя компилятор? |
Шерлок Холмс |
|
ну, допустим компилятор не нашел объявление ~D(); и создал его, а потом нашел тело (твоей ~D()) этого деструктора и скомпилил. |
byte |
|
Шерлок Холмс, я примерно понимаю, что происходит Добавлено 19.01.05, 17:51 Цитата Programs shall not define implicitly-declared special member functions. (начало главы 12 в стандарте) То есть нельзя определять неявно объявленные специальные функции-члены класса(надеюсь, понятно, какие) Цитата If a class has no user-declared destructor, a destructor is declared implicitly. (12.4.3) То есть если мы не объявляем деструктор явно, компилятор делает это за нас. Ты не объявляешь для структуры D деструктор явно => это делает компилятор. То есть ты получаешь «implicitly-declared special member function». А их нельзя определять явно. То есть, грубо говоря, приведенная тобой программа ill-formed. Добавлено 19.01.05, 17:54 Сообщение отредактировано: byte — 19.01.05, 18:04 |
Flex Ferrum |
|
Да, а вот начало раздела 12 я не прочитал… VC «исправляется» если убрать наследование. Значит, баг в компиляторе… Хотя и весьма интересный. |
byte |
|
Цитата Flex Ferrum @ 19.01.05, 18:58 VC «исправляется» если убрать наследование.
Цитата Flex Ferrum @ 19.01.05, 18:58 Значит, баг в компиляторе…
По идее о багах компилера надо сообщать разработчикам? |
0 пользователей читают эту тему (0 гостей и 0 скрытых пользователей)
0 пользователей:
- Предыдущая тема
- C/C++: Общие вопросы
- Следующая тема
[ Script execution time: 0,0380 ] [ 16 queries used ] [ Generated: 9.02.23, 13:16 GMT ]
Hello everyone having anissue with my code today. I have created a program calculating area of square circle and rectangle. With a base class of shape. Where the UML has shape as the abstract class with public area():double, getName():string,and getDimensions:string, rectangle derived from shape with protected height, and width, and a public rectangle(h:double, w:double), followed by a derived square from rectangle with just a public square(h:double), and finally a circle derived from shape with a private radius, and a public circle(r:double).
So far have gotten far in my code yet in my shape.cpp file am getting an error on line 10 that says shape.cpp:10: error: definition of implicitly-declared ‘constexpr shape::shape()’
shape::shape()
here is a link to my complete code: https://gist.github.com/anonymous/0eedd7719a34655488fb
shape.cpp file:
#include "shape.h"
#include "circle.h"
#include "rectangle.h"
#include "square.h"
#include <QDebug>
#include <QString>
#include <iostream>
using namespace std;
shape::shape()
{
};
your help is appreciated
Compiler error: definition of implicitly-declared Class
Post Reply
[phpBB Debug] PHP Warning: in file [ROOT]/vendor/twig/twig/lib/Twig/Extension/Core.php on line 1275: count(): Parameter must be an array or an object that implements Countable
- FredCailloux
- Posts:69
- Joined:Sat Mar 28, 2015 4:45 am
- Location:Quebec — Canada
[phpBB Debug] PHP Warning: in file [ROOT]/vendor/twig/twig/lib/Twig/Extension/Core.php on line 1275: count(): Parameter must be an array or an object that implements Countable
I have this LS7366.h file and LS7366.cpp that I am building, in which I define the Class LS7366, with the following line:
Code: Select all
// in the header LS7366.h
#if !defined DSPI_PORT
#define DSPI_PORT DSPI0 // Default DSPI port = DSPI0
#endif
#define NON_QUADRATURE 0x00
// and a whole buch of other #define lines ...
class LS7366 {
private: DSPI_PORT DSPIjack ;
and some more code lines ; }
// in the code file LS7366.cpp - Class definition
LS7366::LS7366 ( ) { }
void LS7366::begin () {
and some more code lines ; }
and some more functions defined ...
void LS7366 :: end ( ) {
and some more code lines ; }
I took this template from another working Class so I am pretty sure the layout is OK and yet I am getting a compiler error and I cant figure out what the problem may be. What is the compiler means by «implicitely-declared» ? Where is my mistake ? What needs to be done to correct this compiler error ?
LS7366.cpp:7:20: error: definition of implicitly-declared ‘LS7366::LS7366()
Thanks
Prashant Tripathi Knowing is to the Self what knowledge is to the ego
- FredCailloux
- Posts:69
- Joined:Sat Mar 28, 2015 4:45 am
- Location:Quebec — Canada
[phpBB Debug] PHP Warning: in file [ROOT]/vendor/twig/twig/lib/Twig/Extension/Core.php on line 1275: count(): Parameter must be an array or an object that implements Countable
Re: Compiler error: definition of implicitly-declared Class
Post
by FredCailloux » Sat Feb 13, 2016 3:44 am
I found the problem.
Forgot to include the line:
Code: Select all
class LS7366 {
private: DSPI_PORT DSPIjack ;
public:
LS7366 ( ) ; // Forgot this line in my definition
void begin ( ) ;
void end ( ) ;
I got rit of the error.
And now I have another type of compiler error to solve. But that will be part of another investigation and probably another posted question.
Cheers everyone
Prashant Tripathi Knowing is to the Self what knowledge is to the ego
Post Reply
[phpBB Debug] PHP Warning: in file [ROOT]/vendor/twig/twig/lib/Twig/Extension/Core.php on line 1275: count(): Parameter must be an array or an object that implements Countable
[phpBB Debug] PHP Warning: in file [ROOT]/vendor/twig/twig/lib/Twig/Extension/Core.php on line 1275: count(): Parameter must be an array or an object that implements Countable
With the pre-processor macro
#define sum(...)
_sum(sizeof((int []){ __VA_ARGS__ }) / sizeof(int), (int []){ __VA_ARGS__ })
being called with sum(1,2,3)
, the line is translated (a simple string substitution, replacing "__VA_ARGS__"
with "1,2,3"
) into:
_sum(sizeof((int []){1,2,3}) / sizeof(int), (int []){1,2,3})
which is a function call to _sum()
passing two things:
- the number of integers in the array {1,2,3} which is 3 (it gets this by dividing the size of the three-integer array by the size of a single integer).
- the pointer to the array itself (or a totally different array containing the same values, depending on how smart your compiler is).
All the _sum()
function does is add each of the integers to s
(which is initially zero) until the count runs out.
That first bullet point above bears some explanation. When you have an array of N
elements defined as follows:
tType x[22];
the size of the array is sizeof(x)
, the size of all elements. The size of a single element of that array is sizeof(x[0])
, the size of the first element, although I often prefer the sizeof(*x)
variant.
So, to count the number of elements, you simply divide the total size by the size of an element, using one of the following:
sizeof(x) / sizeof(x[0])
sizeof(x) / sizeof(*x)
And, since you’ve asked for a detailed analysis of the code, here we go:
// Needed for printf().
#include <stdio.h>
// Macro to convert sum(n1,n2,...,nN) to _sum(N,n1,n2,...,nN).
// This calculates the length of the array by dividing its size by the size
// of an int and passes both the length and array through to the new
// function.
// __VA_ARGS__ is replaced with the entire marcro argument list, '1,2,3' in
// this case.
#define sum(...)
_sum(sizeof((int []){ __VA_ARGS__ }) / sizeof(int), (int []){ __VA_ARGS__ })
// Function to take size and pointer to int array, and return sum.
int _sum (size_t count, int values[]) {
int s = 0; // Initial sum of zero.
while(count--) // Until elements exhausted (count down).
s += values[count]; // Add each array element to accumulator.
return s; // Return sum.
}
int main (void) {
printf ("%i", sum(1, 2, 3)); // Test it with 1, 2 and 3 (should print 6).
}
Вот код:
#include <cstdlib>
#include <iostream>
using namespace std;
class classA
{
protected:
void setX(int a);
private:
int p;
};
classA:: classA()
{ //error here.
p = 0;
}
void classA:: setX(int a)
{
p = a;
}
int main()
{
system("PAUSE");
return EXIT_SUCCESS;
}
4 ответы
Вы забыли объявить конструктор в определении класса. Объявите это в public
раздел класса (если вы хотите, чтобы клиенты создавали экземпляр, используя его):
class classA
{
public:
classA(); // you forgot this!
protected:
void setX(int a);
private:
int p;
};
Теперь вы можете написать его определение вне класса, что вы уже сделали.
ответ дан 23 апр.
class classA
{
protected:
classA(); // you were missing an explicit declaration!
void setX(int a);
private:
int p;
};
classA:: classA()
{
p = 0;
}
ответ дан 23 апр.
classA
не имеет имени участника classA()
реализовать.
class classA
{
// ....
public:
classA() ; // Missing the declaration of the default constructor.
};
ответ дан 23 апр.
По умолчанию предоставляется пустой конструктор: это правильно. Но если вы переопределите его, это больше не конструктор по умолчанию. Вы должны объявить и определить его. Если вы только объявите его (без тела), это неправильно: вы также должны определить его. Если вы определяете его без объявления в классе, это тоже ошибка. Однако вы можете «объединить» объявление и определение, написав следующее:
class classA
{
// ....
public:
classA() { p = 0;}
};
или в этом случае еще лучше:
class classA
{
// ....
public:
classA():p(0) {}
};
ответ дан 22 окт ’17, 13:10
Не тот ответ, который вы ищете? Просмотрите другие вопросы с метками
c++
or задайте свой вопрос.